package o;

import androidx.annotation.NonNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class amo {
    private final File ˊ;
    private final File ˎ;

    static final class e extends OutputStream {
        private final FileOutputStream ˎ;
        private boolean ˏ = false;

        public e(File file) throws FileNotFoundException {
            this.ˎ = new FileOutputStream(file);
        }

        public void close() throws IOException {
            if (!this.ˏ) {
                this.ˏ = true;
                flush();
                try {
                    this.ˎ.getFD().sync();
                } catch (Throwable e) {
                    amz.ˋ("AtomicFile", "Failed to sync file descriptor:", e);
                }
                this.ˎ.close();
            }
        }

        public void flush() throws IOException {
            this.ˎ.flush();
        }

        public void write(int i) throws IOException {
            this.ˎ.write(i);
        }

        public void write(@NonNull byte[] bArr) throws IOException {
            this.ˎ.write(bArr);
        }

        public void write(@NonNull byte[] bArr, int i, int i2) throws IOException {
            this.ˎ.write(bArr, i, i2);
        }
    }

    public amo(File file) {
        this.ˎ = file;
        this.ˊ = new File(file.getPath() + ".bak");
    }

    public void ॱ() {
        this.ˎ.delete();
        this.ˊ.delete();
    }

    public OutputStream ˊ() throws IOException {
        if (this.ˎ.exists()) {
            if (this.ˊ.exists()) {
                this.ˎ.delete();
            } else if (!this.ˎ.renameTo(this.ˊ)) {
                amz.ˏ("AtomicFile", "Couldn't rename file " + this.ˎ + " to backup file " + this.ˊ);
            }
        }
        try {
            return new e(this.ˎ);
        } catch (Throwable e) {
            File parentFile = this.ˎ.getParentFile();
            if (parentFile == null || !parentFile.mkdirs()) {
                throw new IOException("Couldn't create directory " + this.ˎ, e);
            }
            try {
                return new e(this.ˎ);
            } catch (Throwable e2) {
                throw new IOException("Couldn't create " + this.ˎ, e2);
            }
        }
    }

    public void ˊ(OutputStream outputStream) throws IOException {
        outputStream.close();
        this.ˊ.delete();
    }

    public InputStream ˋ() throws FileNotFoundException {
        ˏ();
        return new FileInputStream(this.ˎ);
    }

    private void ˏ() {
        if (this.ˊ.exists()) {
            this.ˎ.delete();
            this.ˊ.renameTo(this.ˎ);
        }
    }
}
